package com.eascs.spider.yuqing.worker.handler;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.eascs.spider.yuqing.common.util.PropertiesUtil;
import com.eascs.spider.yuqing.common.util.ZKUtil;

/**
 * 注册模块
 * @author hzp
 *
 */
@Component
public class Register {
	
	private static Logger logger = LoggerFactory.getLogger(Register.class);

	private static final String WORKER_PATH = "/worker";
	
	public void send(){
		try {
			String port = PropertiesUtil.getConfig("server.port");
			String ip = getLocalHost();
			ZKUtil.register(WORKER_PATH, ip, port);
			logger.info("工作节点:{}注册成功" ,ip+":"+port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取本机ip，免受虚拟机IP干扰
	 * @return
	 */
	public String getLocalHost(){
		try {  
	       for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {  
	           NetworkInterface intf = en.nextElement();  
	           for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {  
	               InetAddress inetAddress = enumIpAddr.nextElement();
	               if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {  
	            	   return inetAddress.getHostAddress().toString();//默认返回第一个符合条件的本地ip
	               }  
	           }  
	       }  
	   } catch (SocketException ex) {  
		   ex.printStackTrace();
	   }  
	   return null;
	}
	
}
